/**
 * 加载loading组件单例
 * TODO 需要实现可自定义Loading组件来源，并将show，hide方法绑定到LoadingQuene类的showLoading和hideLoading方法内
 */
import globalLoading from "./GlobalLoading";
import { Toast } from "vant";

/**
 * 单例模式：管理需要全局显示请求loading的接口队列
 * 1.解决重复创建loading的问题；
 * 2.解决多个请求时，先完成的请求会结束全局loading的问题；
 */
class LoadingQuene {
  static getInstance() {
    if (!this.instance) {
      this.instance = new LoadingQuene();
    }
    return this.instance;
  }

  constructor() {
    this.loadingQuene = {};
    this.isLoading = false;
    this.toast = null; //vant loading toast instance
  }

  enquene(url, parmas) {
    if (this.getQueneLength() == 0) {
      this.showLoaing();
      this.isLoading = true;
    }
    this.loadingQuene[url] = parmas;
    console.log("request 请求中的接口：", this.getQueneLength());
  }

  dequene(url) {
    if (this.loadingQuene[url]) {
      delete this.loadingQuene[url];
      if (Object.keys(this.loadingQuene).length == 0) {
        this.hideLoading();
        this.isLoading = false;
      } else {
        this.isLoading = true;
      }
    } else {
      console.log(`接口 [${url}] 未设置loading`);
    }
    console.log("response 剩余请求中的接口：", this.getQueneLength());
  }

  getQuene() {
    return this.loadingQuene;
  }

  getQueneLength() {
    return Object.keys(this.loadingQuene).length;
  }

  showLoaing() {
    // globalLoading.show(); //diy loading instance show
    this.toast = Toast.loading({
      duration: 0,
      forbidClick: true,
    });
  }

  hideLoading() {
    // globalLoading.hide();
    this.toast.clear();
    this.toast = null;
  }
}

export default LoadingQuene.getInstance();
